package com.hs.device.charger.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hs.common.core.constant.SecurityConstants;
import com.hs.common.core.domain.Result;
import com.hs.common.core.exception.ServiceException;
import com.hs.common.core.utils.StringUtils;
import com.hs.common.security.annotation.InnerAuth;
import com.hs.communication.common.entity.Charger;
import com.hs.communication.common.entity.ChargerData;
import com.hs.communication.common.entity.dto.ParaDto;
import com.hs.communication.common.entity.vo.DeviceVo;
import com.hs.communication.common.feign.RemoteMqttService;
import com.hs.communication.common.feign.RemoteSocketService;
import com.hs.device.charger.entity.dto.HistoryDataDto;
import com.hs.device.charger.entity.dto.UserChargerDto;
import com.hs.device.charger.entity.vo.*;
import com.hs.device.charger.service.ChargerDataService;
import com.hs.device.charger.service.ChargerService;
import com.hs.device.charger.service.UserChargerService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/charger")
public class ChargerController {

    @Resource
    private ChargerService chargerService;
    @Resource
    private UserChargerService userChargerService;

    @Resource
    private ChargerDataService chargerDataService;

    @Resource
    private RemoteMqttService remoteMqttService;

    @Resource
    private RemoteSocketService remoteSocketService;

//    @Resource
//    private StatusMap statusMap;

    @InnerAuth
    @GetMapping(value = "/statistics")
    public Result<DeviceVo> getStatistics(@RequestParam long userId) {
        System.out.println("charger模块中 getStatistics 函数调用");
        return Result.ok(chargerService.getStatistics(userId));
    }

    /**
     * 获取设备sn列表
     * 这个是服务内部远程调用
     *
     * @return
     */
    @InnerAuth
    @GetMapping(value = "/sns")
    Result<List<String>> getSns(@RequestParam("userId") long userId) {
        return Result.ok(chargerService.getSns(userId));
    }

    /**
     * 获取设备sn列表
     * 这个是客户端直接请求
     *
     * @return
     */
    @GetMapping("/snList")
    public Result<List<String>> getSns() {
        return Result.ok(chargerService.getSns());
    }


    @PostMapping("/bind")
    public Result<Boolean> bind(@RequestBody UserChargerDto userChargerDto) {
        System.out.println("bind 方法被调用");
        int result = userChargerService.bind(userChargerDto);
        return Result.ok(result > 0);
    }

    @PutMapping("/update")
    public Result<Boolean> update(@RequestBody UserChargerDto userChargerDto) {
        System.out.println("update 方法被调用");
        int result = userChargerService.update(userChargerDto);
        return Result.ok(result > 0);
    }

    @DeleteMapping("/unbind")
    public Result<Boolean> unbind(@RequestBody UserChargerDto userChargerDto) {
        System.out.println("unbind 方法被调用");
        int result = userChargerService.unbind(userChargerDto);
        return Result.ok(result > 0);
    }

    @GetMapping("/list")
    public Result<ChargerListVo> getListPage(@RequestParam int pageNum, @RequestParam int pageSize, @RequestParam String status) {

//        List<String> sns = chargerService.getSns();
//        //获取第1页，10条内容，默认查询总数count
        PageHelper.startPage(pageNum, pageSize, true);
        List<Charger> chargers = chargerService.getListByUserId(status);
        //用PageInfo对结果进行包装
        PageInfo<Charger> page = new PageInfo(chargers);
//
        List<Charger> chargerList = page.getList();


        List<ChargerVo> voList = chargerList.stream().map(e ->
                ChargerVo.builder().sn(e.getSn()).name(e.getName()).address(e.getAddress()).status(e.getStatus()).offOnlineTime(e.getOffOnlineTime()).build()
        ).collect(Collectors.toList());


        ChargerListVo chargerListVo = ChargerListVo.builder()
                .list(voList)
                .total(page.getTotal())
                .build();
        return Result.ok(chargerListVo);
    }

    @InnerAuth
    @PutMapping("/status")
    public Result<Boolean> updateStatus(@RequestBody Charger charger) {
        System.out.println("充电桩模块 updateStatus 函数 status=" + charger.getStatus());
        return Result.ok(chargerService.updateStatus(charger) > 0);
    }

    @InnerAuth
    @PostMapping("/data")
    public Result<Boolean> insert(@RequestBody ChargerData chargerData) {
//        System.out.println("充电桩模块 insert 函数");
        return Result.ok(chargerService.insert(chargerData) > 0);
    }

    /**
     * 获取实时数据
     *
     * @param sn
     * @return
     */
    @GetMapping("/data")
    public Result<ChargerDataVo> getData(@RequestParam String sn) {
        ChargerData chargerData = chargerDataService.getData(sn);
        if (StringUtils.isNull(chargerData)) {
            throw new ServiceException("设备未连接,无法查询实时数据");
        }
        ChargerDataVo dataVo = ChargerDataVo.builder().sn(chargerData.getSn()).connection(chargerData.getConnection())
                .reportTime(chargerData.getReportTime())
                .voltageInput(chargerData.getVoltageInput()).voltageOutput(chargerData.getVoltageOutput())
                .currentInput(chargerData.getCurrentInput()).currentOutput(chargerData.getCurrentOutput())
                .frequencyInput(chargerData.getFrequencyInput()).frequencyOutput(chargerData.getFrequencyOutput())
                .chargingTime(chargerData.getChargingTime()).chargingEnergy(chargerData.getChargingEnergy()).build();

        return Result.ok(dataVo);
    }

    @PostMapping("/parameter")
    public Result<Boolean> setParameter(@RequestBody ParaDto paraDto) {
        if (paraDto.getConnection().equals("mqtt")) {
            return remoteMqttService.setParameter(paraDto, SecurityConstants.INNER);
        } else if (paraDto.getConnection().equals("socket")) {
            return remoteMqttService.setParameter(paraDto, SecurityConstants.INNER);
        }
        return Result.fail(false);
    }


    @PostMapping("/history")
    public Result<HistoryDataListVo> getHistory(@RequestBody HistoryDataDto historyDataDto) {
        PageHelper.startPage(historyDataDto.getPageNum(), historyDataDto.getPageSize(), true);
        List<ChargerData> list = chargerService.getHistory(historyDataDto);
        //用PageInfo对结果进行包装
        PageInfo<ChargerData> page = new PageInfo(list);
//
        List<ChargerData> pageList = page.getList();


        List<HistoryDataVo> listVo = pageList.stream().map(obj ->
                HistoryDataVo.builder().id(obj.getId()).sn(obj.getSn()).connection(obj.getConnection())
                        .reportTime(obj.getReportTime()).voltageInput(obj.getVoltageInput())
                        .voltageOutput(obj.getVoltageOutput()).currentInput(obj.getCurrentInput())
                        .currentOutput(obj.getCurrentOutput()).frequencyInput(obj.getFrequencyInput())
                        .frequencyOutput(obj.getFrequencyOutput()).chargingTime(obj.getChargingTime())
                        .chargingEnergy(obj.getChargingEnergy()).build()
        ).collect(Collectors.toList());
        return Result.ok(HistoryDataListVo.builder().list(listVo).total(page.getTotal()).build());
    }

    /**
     * 逻辑删除
     * key为ids,值为id列表
     * 因为只有一个id列表参数,不做写dto类
     *
     * @param map
     * @return
     */
    @PutMapping("/history")
    public Result<Boolean> deleteHistory(@RequestBody Map<String, List<Long>> map) {
        System.out.println("deleteHistory方法");
        List<Long> ids = map.get("ids");
        return Result.ok(chargerService.deleteHistory(ids) > 0);
    }
}
